React 错误处理(componentDidCatch)

您所在的位置:网站首页 react getsnapshotbeforeupdate React 错误处理(componentDidCatch)

React 错误处理(componentDidCatch)

#React 错误处理(componentDidCatch)| 来源: 网络整理| 查看: 265

前言

   看react 文档突然发现有这个 错误处理函数,好像是17年9月出的,这个真的绝了可以帮助我们捕捉错误咯

 

 React 16 将提供一个内置函数 componentDidCatch,如果 render() 函数抛出错误,则会触发该函数。

官网例子

下面这个:

class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } componentDidCatch(error, info) { // Display fallback UI this.setState({ hasError: true }); // You can also log the error to an error reporting service logErrorToMyService(error, info); } render() { if (this.state.hasError) { // You can render any custom fallback UI return Something went wrong.; } return this.props.children; } }

当然你可以把这个组件封装下成为

然后在顶部或任何地方,你可以这样使用它

 

 另一个特性:

componentDidCatch 是包含错误堆栈的 info 对象!

{this.state.info && this.state.info.componentStack}

 

当然我是这么用的在路由那边

class App extends React.Component { constructor(props) { super(props) this.state = { hasError: false } } componentDidCatch(error, info) { console.log(error, info) this.setState({ hasError: true }) } render() { return this.state.hasError ? 页面出错了404 : ( {/* 检验是否有登录信息 */} {/* 有了switch后,匹配到path后就不会再匹配下去了 */} ) } }

其实还是组件化比较好一点,毕竟复用性比较高



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3